package org.viva.action;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.viva.core.Log;
import org.viva.core.api.SkyEye;
import org.viva.secu.Security;
import org.viva.service.secu.MenuService;
import org.viva.service.secu.UserService;

@Controller
public class LoginAction {

    @Resource
    private MenuService menuService;
    @Resource
    private UserService userService;

    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String index(HttpServletRequest request) {
        return "/login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String doLogin(HttpServletRequest request) {
        String code = request.getParameter("code");
        String password = request.getParameter("password");
        Subject currentUser = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(code, password);
        try {
            currentUser.login(token);
            return "redirect:";
        } catch (AuthenticationException e) {
            Log.error("登录失败错误信息:" + e, e);
            token.clear();
            return "redirect:/login";
        }
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public String doLogout(HttpServletRequest request) {
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
        Security.cleanSession(SkyEye.getRequest().getSession());
        return "redirect:/login";
    }

    public void setMenuService(MenuService menuService) {
        this.menuService = menuService;
    }

}
